<template>
  <div class="pagination">
    <button :disabled="pageNo <= 1" @click="$emit('pageNo', pageNo - 1)">上一页</button>
    <button v-if="pageNo >= 4" @click="$emit('pageNo', 1)">1</button>
    <button v-if="pageNo >= 4">···</button>

    <template v-for="(page, index) in pageStartAndEnd.end">
      <button :key="index" v-if="page >= pageStartAndEnd.start" @click="$emit('pageNo', page)" :class="pageNo == page ? 'active' : ''">
        {{ page }}
      </button>
    </template>
    <button v-if="!(pageNo >= pageNum)">···</button>
    <button v-if="!(pageNo == pageNum)" @click="$emit('pageNo', pageNum)">{{ pageNum }}</button>
    <button :disabled="pageNo == pageNum" @click="$emit('pageNo', pageNo + 1)">下一页</button>
    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>
<script>
export default {
  name: 'Pagination',
  props: ['total', 'pageNo', 'pageSize', 'pageSort'],
  computed: {
    // 计算总页码数
    pageNum() {
      return Math.ceil(this.total / this.pageSize)
    },
    pageStartAndEnd() {
      const { pageNo, pageSort, pageNum } = this
      let start
      let end = 0
      // 排序页码数 大于 总页码数 则少于5页正常排序
      if (pageSort > pageNum) {
        start = 1
        end = pageNum
      } else {
        start = pageNo - parseInt(pageSort / 2)
        end = pageNo + parseInt(pageSort / 2)
        // 分页器最小位只能是 1
        if (start < 1) {
          start = 1
          end = pageSort
        }
        if (end > pageNum) {
          start = pageNum - pageSort + 1
          end = pageNum
        }
      }
      return { start, end }
    }
  }
}
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #fff;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 45.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 1px solid #eee;

    &:hover {
      background: #eee;
    }

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
.active {
  background-color: skyblue;
}
</style>
